package cn.edu.njust.service.impl;

import cn.edu.njust.mapper.UserMapper;
import cn.edu.njust.pojo.User;
import cn.edu.njust.service.UserService;
import cn.edu.njust.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserServiceImpl implements UserService {
    // 获取工厂对象
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     *  清除缓存
     */
    @Override
    public void clear() {
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用方法
        mapper.clear();

        sqlSession.commit();

        sqlSession.close();

    }

    /**
     * 查询所有
     * @return
     */
    @Override
    public List<User> selectAll() {
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        List<User> users = mapper.selectAll();

        sqlSession.close();

        return users;
    }

    @Override
    public User selectId01(String idNo){
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.selectId01(idNo);

        sqlSession.close();

        return user;
    }

    /**
     * 删除用户
     * @param idNo
     */
    @Override
    public int deleteById(String idNo) {
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用方法
        int count = mapper.delete01(idNo);

        sqlSession.commit();

        sqlSession.close();

        return count;

    }

    /**
     * 重置用户密码
     * @param idNo
     */
    @Override
    public void resetById(String idNo) {
        //获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //获取UserMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用方法
        mapper.reset01(idNo);

        sqlSession.commit();

        sqlSession.close();
    }


}
